package util

import (
	"bytes"
	"encoding/binary"
	"strconv"
)

/**
  @Project: out_mqtt
  @Description:
  @Version 1.0
  @Author: lyndon Create 1.0 8/9/21
  @Copyright (c)2021-2022 gridsum.com
  @Modified By:
*/

func IntToBytes(n int) []byte {
	data := int64(n)
	bytebuf := bytes.NewBuffer([]byte{})
	binary.Write(bytebuf, binary.BigEndian, data)
	return bytebuf.Bytes()
}

func BytesToInt(bys []byte) int {
	bytebuff := bytes.NewBuffer(bys)
	var data int64
	binary.Read(bytebuff, binary.BigEndian, &data)
	return int(data)
}

func Interface2String(inter interface{}) string {

	switch inter.(type) {

	case string:
		return inter.(string)
	case int:
		return strconv.Itoa(inter.(int))
	case float32:
		return strconv.FormatFloat(inter.(float64), 'E', -1, 32)
	case float64:
		return strconv.FormatFloat(inter.(float64), 'E', -1, 64)
	default:
		return "Unknown"
	}
}

func B2S(bs []int8) string {
	ba := []byte{}
	for _, b := range bs {
		ba = append(ba, byte(b))
	}
	return string(ba)
}

func UB2S(bs []uint8) string {
	ba := []byte{}
	for _, b := range bs {
		ba = append(ba, byte(b))
	}
	return string(ba)
}
